/*
 * Copyright 2013-2014 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xdtech.sys.init;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;

import com.xdtech.common.service.impl.BaseService;
import com.xdtech.common.utils.ApplicationContextUtil;
import com.xdtech.common.utils.EmptyUtil;
import com.xdtech.common.utils.EncryptUtil;
import com.xdtech.core.init.InitCacheData;
import com.xdtech.core.init.SysInitOperation;
import com.xdtech.core.model.BaseModel;
import com.xdtech.sys.model.CodeValue;
import com.xdtech.sys.model.DictionaryCode;
import com.xdtech.sys.model.MenuFunction;
import com.xdtech.sys.model.Operation;
import com.xdtech.sys.model.Params;
import com.xdtech.sys.model.Role;
import com.xdtech.sys.model.User;
import com.xdtech.sys.model.UserGroup;
import com.xdtech.sys.service.CodeValueService;
import com.xdtech.sys.service.DictionaryCodeService;
import com.xdtech.sys.service.MenuFunctionService;
import com.xdtech.sys.service.OperationService;
import com.xdtech.sys.service.RoleService;
import com.xdtech.sys.service.TaskService;
import com.xdtech.sys.service.UserGroupService;
import com.xdtech.sys.service.UserService;
import com.xdtech.sys.util.SysConstants;
import com.xdtech.sys.vo.CodeValueItem;

/**
 * 数据字典初始化实现类
 * @author max.zheng
 * @create 2014-9-25下午9:42:01
 * @since 1.0
 * @see
 */
public class SysInit implements SysInitOperation{
	Log log = LogFactory.getLog(SysInit.class);
	static ApplicationContext context = null;
	static UserService userService = null;
	static RoleService roleService = null;
	static UserGroupService userGroupService = null;
	static MenuFunctionService menuFunctionService = null;
	static OperationService operationService = null;
	/**
	 * 数据字典初始化
	 * @author max.zheng
	 * @create 2014-9-25下午9:42:14
	 * @modified by
	 */
	public void initingToDb(BaseService<BaseModel> baseService) { 
		List params = (List) baseService.findByHql("from Params where code=? and codeValue=?", "SysInit","true");
		log.info("Sys模块数据库初始化......");
		if (EmptyUtil.isEmpty(params)) {
			initStarting();
			Params p = new Params("SysInit", "true", "系统模块数据库初始化标记");
			baseService.save(p);
			log.info("Sys模块数据库初始化......结束");
		}else {
			log.info("Sys模块数据库已经初始化......完毕");
		}
		
	}
	/**
	 * 
	 * @author max.zheng
	 * @create 2015-3-10下午10:33:34
	 * @modified by
	 */
	private static void initStarting() {
		context = ApplicationContextUtil.getContext();
		userService = context.getBean(UserService.class);
		roleService = context.getBean(RoleService.class);
		userGroupService = context.getBean(UserGroupService.class);
		menuFunctionService = context.getBean(MenuFunctionService.class);
		operationService = context.getBean(OperationService.class);
		//初始化系统管理模块
		initSys();
		//初始化数据字典
		initDictionary();
		
	}
	/**
	 * 
	 * @author <a href="max.zheng@zkteco.com">郑志雄</>
	 * @since 2015-5-12 下午4:10:46
	 */
	private static void initTasks()
	{
		TaskService taskService = ApplicationContextUtil.getContext().getBean(TaskService.class);
		taskService.startAllTasks();
	}
	/**
	 * 
	 * @author max.zheng
	 * @create 2015-2-15下午8:26:02
	 * @modified by
	 */
	private static void initDictionary() {
		DictionaryCodeService dictionaryCodeService = context.getBean(DictionaryCodeService.class);
		CodeValueService codeValueService = context.getBean(CodeValueService.class);
 		DictionaryCode dictionaryCode = new DictionaryCode("SEX","性别");
		dictionaryCodeService.save(dictionaryCode);
		codeValueService.save(new CodeValue("M","男",1,dictionaryCode));
		codeValueService.save(new CodeValue("F","女",2,dictionaryCode));
		
		dictionaryCode = new DictionaryCode("YON","是否");
		dictionaryCodeService.save(dictionaryCode);
		codeValueService.save(new CodeValue("true","是",1,dictionaryCode));
		codeValueService.save(new CodeValue("false","否",2,dictionaryCode));
		
		dictionaryCode = new DictionaryCode("YES_OR_NO","是否");
		dictionaryCodeService.save(dictionaryCode);
		codeValueService.save(new CodeValue(SysConstants.YES,"是",1,dictionaryCode));
		codeValueService.save(new CodeValue(SysConstants.NO,"否",2,dictionaryCode));
		
		dictionaryCode = new DictionaryCode("USER_STATUS","用户状态");
		dictionaryCodeService.save(dictionaryCode);
		codeValueService.save(new CodeValue("1","启用",1,dictionaryCode));
		codeValueService.save(new CodeValue("0","禁用",2,dictionaryCode));
		
		
		dictionaryCode = new DictionaryCode("RULE_OPTION","规则操作符");
		dictionaryCodeService.save(dictionaryCode);
		codeValueService.save(new CodeValue("and","并且",1,dictionaryCode));
		codeValueService.save(new CodeValue("or","或者",2,dictionaryCode));
		
		dictionaryCode = new DictionaryCode("RULE_TYPE","规则类型符");
		dictionaryCodeService.save(dictionaryCode);
		codeValueService.save(new CodeValue("in","包括在...",1,dictionaryCode));
		codeValueService.save(new CodeValue("eq","等于",2,dictionaryCode));
		
		dictionaryCode = new DictionaryCode("TASK_STATUS","任务状态");
		dictionaryCodeService.save(dictionaryCode);
		codeValueService.save(new CodeValue("0","停止",1,dictionaryCode));
		codeValueService.save(new CodeValue("1","运行",2,dictionaryCode));
		
		dictionaryCode = new DictionaryCode("TASK_GROUP","任务组");
		dictionaryCodeService.save(dictionaryCode);
		codeValueService.save(new CodeValue("DEFAUTL","默认组",1,dictionaryCode));
	}
	private static void initSys() {
		User root = new User();
		root.setLoginName("root");
		root.setName("超级用户");
		root.setSex("M");
		root.setStatus("1");
		root.setPassword(EncryptUtil.encodePassword("root"));
		userService.save(root);
		
		User admin = new User();
		admin.setLoginName("admin");
		admin.setName("管理员");
		admin.setSex("M");
		admin.setStatus("1");
		admin.setPassword(EncryptUtil.encodePassword("admin"));
		userService.save(admin);
		
		User normal = new User();
		normal.setLoginName("normal");
		normal.setName("普通用户");
		normal.setSex("F");
		normal.setStatus("1");
		normal.setPassword(EncryptUtil.encodePassword("normal"));
		userService.save(normal);
		
		User test = new User();
		test.setLoginName("test");
		test.setName("测试用户");
		test.setSex("M");
		test.setStatus("1");
		test.setPassword(EncryptUtil.encodePassword("test"));
		userService.save(test);
		
		Role superManager = new Role();
		superManager.setEnable(true);
		superManager.setCode("super-administrator");
		superManager.setSuperuser(true);
		superManager.setDescription("超级管理员角色描述");
		superManager.setName("超级管理员角色");
		roleService.save(superManager);
		root.getRoles().add(superManager);
		userService.save(root);
		
		Role adminManager = new Role();
		adminManager.setEnable(true);
		adminManager.setCode("administrator");
		adminManager.setName("管理员角色");
		adminManager.setDescription("管理员角色描述");
		roleService.save(adminManager);
		admin.getRoles().add(superManager);
		userService.save(admin);
		
		Role normalManager = new Role();
		normalManager.setEnable(true);
		normalManager.setCode("normal-admin");
		normalManager.setName("普通管理员角色");
		normalManager.setDescription("普通管理员角色描述");
		roleService.save(normalManager);
		normal.getRoles().add(normalManager);
		userService.save(normal);
		
		Role testRole = new Role();
		testRole.setEnable(true);
		testRole.setCode("test");
		testRole.setName("测试角色");
		testRole.setDescription("测试角色描述");
		roleService.save(testRole);
		
		UserGroup rootGroup = new UserGroup();
		rootGroup.setName("JMax平台");
		rootGroup.setParent(null);
		userGroupService.save(rootGroup);
		
		UserGroup group1 = new UserGroup();
		group1.setName("XX公司");
		group1.setParent(rootGroup);
		group1.getUsers().add(test);
		userGroupService.save(group1);
		
		
		UserGroup group11 = new UserGroup();
		group11.setName("XX部门");
		group11.setParent(group1);
		group11.getUsers().add(test);
		userGroupService.save(group11);
		
		
		MenuFunction m1 = new MenuFunction();
		m1.setIconName("icon-system");
		m1.setNameCN("系统管理");
		m1.setOperationCode("system-manage");
		m1.setPageUrl(null);
//		m1.getRoles().add(superManager);
		menuFunctionService.save(m1);
		
		
		
		MenuFunction m11 = new MenuFunction();
		m11.setIconName("icon-user");
		m11.setNameCN("用户管理");
		m11.setOperationCode("user-manage");
		m11.setPageUrl("user.do?user");
		m11.setParent(m1);
		menuFunctionService.save(m11);
		
		createButtonOperations("新增","sys:user:add",m11);
		createButtonOperations("删除","sys:user:delete",m11);
		createButtonOperations("编辑","sys:user:edit",m11);
		createButtonOperations("清空","sys:user:clear",m11);
		createButtonOperations("禁用","sys:user:disable",m11);
		createButtonOperations("启用","sys:user:enable",m11);
		createButtonOperations("刷新","sys:user:refresh",m11);
		createButtonOperations("用户角色","sys:user:linkRole",m11);
		
		MenuFunction m12 = new MenuFunction();
		m12.setIconName("icon-role");
		m12.setNameCN("角色管理");
		m12.setOperationCode("role-manage");
		m12.setPageUrl("role.do?role");
		m12.setParent(m1);
		menuFunctionService.save(m12);
		
		createButtonOperations("新增","sys:role:add",m12);
		createButtonOperations("删除","sys:role:delete",m12);
		createButtonOperations("编辑","sys:role:edit",m12);
		createButtonOperations("刷新","sys:role:refresh",m12);
		createButtonOperations("授权","sys:role:auth",m12);

		MenuFunction m13 = new MenuFunction();
		m13.setIconName("icon-usergroup");
		m13.setNameCN("用户组管理");
		m13.setOperationCode("usergroup-manage");
		m13.setPageUrl("group.do?group");
		m13.setParent(m1);
		menuFunctionService.save(m13);
		
		createButtonOperations("新增","sys:usergroup:add",m13);
		createButtonOperations("删除","sys:usergroup:delete",m13);
		createButtonOperations("编辑","sys:usergroup:save",m13);
		
		MenuFunction m14 = new MenuFunction();
		m14.setIconName("icon-menu");
		m14.setNameCN("菜单管理");
		m14.setOperationCode("menu-manage");
		m14.setPageUrl("menuFunction.do?sysFunction");
		m14.setParent(m1);
		menuFunctionService.save(m14);
		
		createButtonOperations("新增菜单","sys:menu:add",m14);
		createButtonOperations("删除菜单","sys:menu:delete",m14);
		createButtonOperations("保存菜单","sys:menu:save",m14);
		createButtonOperations("新增按钮","sys:operation:add",m14);
		createButtonOperations("删除按钮","sys:operation:delete",m14);
		createButtonOperations("保存按钮","sys:operation:save",m14);
		
		MenuFunction m15 = new MenuFunction();
		m15.setIconName("icon-dictionary");
		m15.setNameCN("数据字典");
		m15.setOperationCode("dictionary-manage");
		m15.setPageUrl("dictionaryCode.do?dictionary");
		m15.setParent(m1);
//		m15.getRoles().add(superManager);
		menuFunctionService.save(m15);
		
		createButtonOperations("新增字典","sys:dictionary:add",m15);
		createButtonOperations("编辑字典","sys:dictionary:edit",m15);
		createButtonOperations("删除字典","sys:dictionary:delete",m15);
		createButtonOperations("刷新字典","sys:dictionary:refresh",m15);
		
		MenuFunction m16 = new MenuFunction();
		m16.setIconName("icon-session");
		m16.setNameCN("会话监控");
		m16.setOperationCode("session-monitor");
		m16.setPageUrl("session.do?session");
		m16.setParent(m1);
		menuFunctionService.save(m16);
		
		createButtonOperations("强制退出","sys:session:delete",m16);
		createButtonOperations("刷新","sys:session:refresh",m16);
		
		MenuFunction m18 = new MenuFunction();
		m18.setIconName("icon-task");
		m18.setNameCN("定时任务");
		m18.setOperationCode("task-manage");
		m18.setPageUrl("task.do?task");
		m18.setParent(m1);
		menuFunctionService.save(m18);
		
		createButtonOperations("新增任务","sys:task:add",m18);
		createButtonOperations("编辑编辑","sys:task:edit",m18);
		createButtonOperations("删除任务","sys:task:delete",m18);
		createButtonOperations("启用任务","sys:task:start",m18);
		createButtonOperations("停止任务","sys:task:stop",m18);
		createButtonOperations("禁用任务","sys:task:disable",m18);
		createButtonOperations("刷新任务","sys:task:refresh",m18);
		//数据权限
		MenuFunction m19 = new MenuFunction();
		m19.setIconName("icon-wrench");
		m19.setNameCN("数据权限");
		m19.setOperationCode("data-permission");
		m19.setPageUrl("null");
		m19.setParent(m1);
		menuFunctionService.save(m19);
		//资源定义
		MenuFunction m191 = new MenuFunction();
		m191.setIconName("icon-article");
		m191.setNameCN("资源定义");
		m191.setOperationCode("resource-definition");
		m191.setPageUrl("resource.do?resource");
		m191.setParent(m19);
		menuFunctionService.save(m191);
		
		MenuFunction m20 = new MenuFunction();
		m20.setIconName("icon-log");
		m20.setNameCN("系统参数");
		m20.setOperationCode("sys-params-manage");
		m20.setPageUrl("params.do?params");
		m20.setParent(m1);
		menuFunctionService.save(m20);
		
		MenuFunction m17 = new MenuFunction();
		m17.setIconName("icon-log");
		m17.setNameCN("日志信息");
		m17.setOperationCode("log-manage");
		m17.setPageUrl("log.do?log");
		m17.setParent(m1);
		menuFunctionService.save(m17);
		createButtonOperations("刷新日志","sys:log:refresh",m17);
		
		MenuFunction m21 = new MenuFunction();
		m21.setIconName("icon-stop");
		m21.setNameCN("数据源监控");
		m21.setOperationCode("druid-monitor");
		m21.setPageUrl("druid/index.html");
		m21.setIframe(true);
		m21.setParent(m1);
		menuFunctionService.save(m21);
		
		
	}

	/**
	 * 
	 * @author max.zheng
	 * @create 2015-2-15下午10:29:11
	 * @modified by
	 * @param m11
	 */
	private static void createButtonOperations(String nameCN, String operationCode,
			MenuFunction menuFunction) {
		Operation operation = new Operation(nameCN, operationCode, menuFunction);
		operationService.save(operation);
		
	}
	/**
	 * @description
	 * @author max.zheng
	 * @create 2014-10-12下午9:18:03
	 * @modified by
	 * @param baseService
	 */
	public void initingToCache(BaseService<BaseModel> baseService) {
		log.info("Sys模块缓存初始化数据......");
		log.info("数据字典缓存初始化......");
		CodeValueService codeValueService = ApplicationContextUtil.getContext().getBean(CodeValueService.class);
		Map<String, List<CodeValueItem>> codeMap = codeValueService.loadDictionMapItems();
		for(String key:codeMap.keySet()) {
			InitCacheData.dictionary.put(key,codeMap.get(key));
		}
		log.info("数据字典缓存初始化......结束");
		log.info("Sys模块缓存初始化数据......结束");
		log.info("初始化系统定时任务......");
		//初始化定时任务
		initTasks();
		log.info("初始化系统定时任务......结束");
	}
	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-4-4下午4:35:02
	 * @modified by
	 * @return
	 */
	public int getInitOrder() {
		return 1;
	}
	/* (非 Javadoc)
	 * initingToWebApplication
	 * <p>对override方法的补充说明，若不需要则删除此行</p>
	 * 
	 * @param baseService
	 * @see com.xdtech.core.init.SysInitOperation#initingToWebApplication(com.xdtech.common.service.impl.BaseService)
	 */
	@Override
	public void initingToWebApplication(BaseService<BaseModel> baseService)
	{
		ServletContext application = ApplicationContextUtil.getApplication();
		List paramList = baseService.getAll(Params.class);
		Params params = null;
		for (Object param : paramList)
		{
			params = (Params) param;
			if (SysConstants.YES.equals(params.getInitToApp()))
			{
				application.setAttribute(params.getCode(), params.getCodeValue());
			}
			
		}
		
	}

}
